/*
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.lvyh.lightframe.core.consumer.transport;

import com.lvyh.lightframe.common.RpcContext;
import com.lvyh.lightframe.common.ext.ExtensionLoaderFactory;
import com.lvyh.lightframe.core.invoke.RpcInvokeContext;
import com.lvyh.lightframe.core.invoke.request.Heartbeat;
import com.lvyh.lightframe.core.invoke.response.RpcResponse;
import com.lvyh.lightframe.core.serialize.Serializer;
import com.lvyh.lightframe.common.exception.RpcRuntimeException;
import io.netty.buffer.ByteBufUtil;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.FullHttpResponse;
import io.netty.handler.codec.http.HttpResponseStatus;
import io.netty.handler.timeout.IdleStateEvent;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class SimpleHttpClientHandler extends SimpleChannelInboundHandler<FullHttpResponse> {
    private static final Logger logger = LoggerFactory.getLogger(SimpleHttpClientHandler.class);


    private RpcInvokeContext invokeContext;
    private Serializer serializer;
    private SimpleHttpConnectClient simpleHttpConnectClient;

    public SimpleHttpClientHandler(final RpcInvokeContext invokeContext, final SimpleHttpConnectClient simpleHttpConnectClient) {
        this.invokeContext = invokeContext;
        this.simpleHttpConnectClient = simpleHttpConnectClient;
        this.serializer = ExtensionLoaderFactory.getExtensionLoader(Serializer.class).getExtension(RpcContext.getSerializer());
    }

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, FullHttpResponse msg) throws Exception {

        if (!HttpResponseStatus.OK.equals(msg.status())) {
            throw new RpcRuntimeException("response status invalid.");
        }

        byte[] responseBytes = ByteBufUtil.getBytes(msg.content());

        if (responseBytes.length == 0) {
            throw new RpcRuntimeException("response is empty.");
        }

        RpcResponse response = (RpcResponse) serializer.deserialize(responseBytes, RpcResponse.class);

        invokeContext.setInvokeResponseFuture(response.getRequestId(), response);

    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        logger.error("client exception", cause);
        ctx.close();
    }

    @Override
    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
        if (evt instanceof IdleStateEvent) {
            simpleHttpConnectClient.send(Heartbeat.PING_REQ);
            logger.info("client send heart beat req.");
        } else {
            super.userEventTriggered(ctx, evt);
        }
    }

}
